package com.aa;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

import com.aa.activity.FirendInfoActivity;
import com.aa.activity.SipCallActivity;
import com.aa.adapter.FirentListAdapter;
import com.aa.adapter.FirentListAdapter.ChildHolder;
import com.aa.contacts.KaguPhones;
import com.aa.contacts.MyLetterListView;
import com.aa.contacts.MyLetterListView.OnTouchingLetterChangedListener;



import android.R.integer;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ContactsActivity extends Activity {

	private String TAG = "ContactsActivity";
	private List<KaguPhones> mContactList;
	private List<KaguPhones> mSearchList;
	private BaseAdapter mAdapter;
	private HashMap<String, Integer> mAlphaIndexer;
	private String[] mSections;
	private TextView mOverLay;
	private Handler mHandler;
	private OverlayThread mOverlayThread;
	private MyLetterListView mLetterListView;
	private EditText metSearchContact;
	private TextView mCenterTextView;
	private LinearLayout mlyAddPerson;
	private ImageView mivAddPerson;
	private TextView mtvContactDetail;
	private List<String> mGroupList = new ArrayList<String>();
	private List<List> mChildList = new ArrayList<List>();
	private ExpandableListView mExpandableListView;
	private FirentListAdapter mFirentListAdapter;
	private ChildHolder mChildHolder;
	private int mGroupPosition = -1;
	private int mChildPosition = -1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contacts);
	//	YaloeApplication.getInstance().startQueryContacts(80);
		mContactList = YaloeApplication.getInstance().contactList;
		Common.getFirendInfo(this, mContactList);
		initFrientList();
		initView();
		initVarible();
		initListener();
		
	}
	
	private void initFrientList(){
		if (Common.iGroupNames.size() == 0){			
			mGroupList.add(getString(R.string.app_contact));
			mChildList.add(mContactList);
			return;
		}
		mChildList.clear();
		
		List<KaguPhones> _ContactList = new ArrayList<KaguPhones>();
		for (int i = 0; i < Common.iGroupNames.size(); i++) {
			List<KaguPhones> _List = new ArrayList<KaguPhones>();
			for (int j = 0; j < Common.iFrientList.size(); j++) {
				KaguPhones _KaguPhones = Common.iFrientList.get(j);
				if (_KaguPhones.getGroupName().equals(Common.iGroupNames.get(i).toString())) {
					_List.add(_KaguPhones);
				}else if (_KaguPhones.getGroupName().equals("")) {
					_ContactList.add(_KaguPhones);
				}
					
				
			}
			mChildList.add(_List);
			mGroupList.add(Common.iGroupNames.get(i));
		}
		mChildList.add(_ContactList);
		mGroupList.add(getString(R.string.app_contact));
	}
	
	 @Override
	protected void onResume() {
		super.onResume();
		//YaloeApplication.getInstance().startQueryContacts(0);
		mContactList = YaloeApplication.getInstance().contactList;
		//mContactList.
		Log.i(TAG, "onResume");
		
	}

	@Override
	protected void onRestart(){		
		super.onRestart();
		
	
	}

	protected void onDestroy()
	  {
	    super.onDestroy();
	    Log.i(TAG, "onDestroy");
	    //((WindowManager)getSystemService(WINDOW_SERVICE)).removeView(mOverLay);
	  }
	
	private void initVarible(){
		
		mSearchList = new ArrayList();
		mHandler = new Handler();
		mOverlayThread = new OverlayThread();
	}
	private void initView(){
		
		mOverLay = (TextView)LayoutInflater.from(this).inflate(R.layout.overlay, null);
		metSearchContact = (EditText)findViewById(R.id.ev_search);
		mivAddPerson = (ImageView)findViewById(R.id.iv_add_person);		
		//RelativeLayout _Layout = (RelativeLayout)LayoutInflater.from(this).inflate(R.layout.contact_item, null);
		
		
		WindowManager.LayoutParams _OverLayLayoutParams =  new WindowManager.LayoutParams(-2, -2, 2, 24, -3);
		//((WindowManager)getSystemService(WINDOW_SERVICE)).addView(mOverLay, _OverLayLayoutParams);
		mLetterListView = (MyLetterListView)findViewById(R.id.MyLetterListView01);
		

		mFirentListAdapter = new FirentListAdapter(mGroupList,mChildList,this);
		mExpandableListView = (ExpandableListView)findViewById(R.id.elv_friendlist);
		mExpandableListView.setAdapter(mFirentListAdapter);
						
		mExpandableListView.setOnChildClickListener(new OnChildClickListener() {
			
			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				KaguPhones _KaguPhones = (KaguPhones)parent.getExpandableListAdapter().getChild(groupPosition, childPosition);
					if (  _KaguPhones.getUser() != 1) {
						if ((mChildPosition != -1 && mGroupPosition != -1 )  && mChildPosition != childPosition) {
							if (mChildHolder.layContacDetail.isShown()) {
								mChildHolder.layContacDetail.setVisibility(View.GONE);
							}
						}
							
						mChildPosition = childPosition;
						mGroupPosition = groupPosition; 
						
						mChildHolder = (ChildHolder)v.getTag();
						
						if (mChildHolder.layContacDetail.isShown()) {
							mChildHolder.layContacDetail.setVisibility(View.GONE);
							
						}else {
							mChildHolder.layContacDetail.setVisibility(View.VISIBLE);
							
						}
					}else {
						
					
						Bundle _Bundle = new Bundle();
						_Bundle.putSerializable("KaguPhones", _KaguPhones);											
						Intent _Intent = new Intent(ContactsActivity.this, FirendInfoActivity.class);
						_Intent.putExtras(_Bundle);
						startActivity(_Intent);
					}					
					
				return false;
			}
		});
	}
	
	private void initListener(){
		mLetterListView.setOnTouchingLetterChangedListener(new LetterListViewListener());
		metSearchContact.addTextChangedListener(new OnSearchTextChanged());
		mivAddPerson.setOnClickListener(new OnAddContactClickListener());
		
	}
	
	 public void switchToDetail(String pCallName, String pCallNumber){
		 
	    if(pCallNumber.equals(getString(R.string.number_private))){
	    	
	      String str = getString(R.string.app_net_tip1);
	      Toast.makeText(this, str, 3000).show();
	      return;
	    }
	    Common.iCallName = pCallName;
	    if (pCallNumber.startsWith("+86")) {
	    	 Common.iCallNumber = pCallNumber.substring(3, pCallNumber.length());
		}else {
			 Common.iCallNumber = pCallNumber;
		}
	   
	    Intent _Intent = new Intent();
	    _Intent.setClass(this, ContactDetail.class);
	    startActivity(_Intent);
	  }

	private String getAlpha(String pAlpha)
	{
	    if (pAlpha == null)
	      return "#";
	    if (pAlpha.trim().length() == 0)
	      return "#";
	    String c = pAlpha.trim().substring(0, 1);
	    if (Pattern.compile("^[A-Za-z]+$").matcher(c).matches()) 	
	      return c.toUpperCase();
	    
	    return "#";
	}
	
	private void getSearchUser(CharSequence pCharSequence){
		String _inputStr;
		if ((pCharSequence != null) && (mContactList != null) && (pCharSequence.length() != 0)) {
			_inputStr = pCharSequence.toString().toLowerCase();
			mSearchList.clear();
		
			for(int i = 0; i < mContactList.size(); i++){
				KaguPhones _KaguPhones = (KaguPhones)mContactList.get(i);
				String _DisplayName = _KaguPhones.getDisplayName().toLowerCase();
				String _PnoneNumber = _KaguPhones.getPhoneNum().toLowerCase();
				String _PinYin = _KaguPhones.getPinYin().toLowerCase();
				if ((_DisplayName.startsWith(_inputStr)) || (_PnoneNumber.startsWith(_inputStr)) || (_PinYin.startsWith(_inputStr))) {
					mSearchList.add(_KaguPhones);
				}
			}
		}
	}
	
	private class OnAddContactClickListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			 Intent _Intent = new Intent("android.intent.action.INSERT", ContactsContract.Contacts.CONTENT_URI);
		     ContactsActivity.this.startActivity(_Intent);
			
		}
		
	}
	
	private class OnSearchTextChanged implements TextWatcher{

		@Override
		public void afterTextChanged(Editable s) {	
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {	
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {	
			if (s.length() != 0) {
				getSearchUser(s.toString());
				if (mSearchList.size() > 0) {
				
				}else {
					
				}
			}
			
		}
		
	}
	
	private class LetterListViewListener implements OnTouchingLetterChangedListener{

		@Override
		public void onTouchingLetterChanged(String pAlpha) {
			if (pAlpha == null ) {
				return;
			}	
			
			Integer _index = mAlphaIndexer.get(pAlpha);
			if ( (_index != null) && (mSections[_index] != null)) {
				
				mOverLay.setText(mSections[_index.intValue()]);
				mOverLay.setVisibility(View.VISIBLE);
				mHandler.removeCallbacks(mOverlayThread);
				mHandler.postDelayed(mOverlayThread, 1500L);
			}
			
		}
		
	}
	
	private class OverlayThread implements Runnable{

		@Override
		public void run() {
			if (mOverLay != null) {
				mOverLay.setVisibility(View.GONE);
			}
			
		}
		
	}
	
	
		
	



}
